//
//  PhoneNewViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-5-30.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "PhoneNewViewController.h"
#import "JSON.h"
#import "NSString+MobileNum.h"
#import "NYMemberCenterDataManager.h"

#define kNewPhoneDynPwdDownloaderKey    @"NewPhoneDynPwdDownloaderKey"
#define kNewPhoneDownloaderKey          @"NewPhoneDownloaderKey"

@interface PhoneNewViewController ()

@property (nonatomic, copy) NSString *tempPwd;

@end

@implementation PhoneNewViewController

@synthesize phoneTextField,pwdTextField,sendButton,commitButton;
@synthesize tempPwd;
@synthesize myScrollView;

#pragma mark - IBAction methods
- (IBAction)sendButtonClicked:(id)sender
{
    [self.phoneTextField resignFirstResponder];
    [self.pwdTextField resignFirstResponder];
    NSString *suburl = [NSString stringWithFormat:kDynamicPasswordUrl,@"jsonp",phoneTextField.text,@"3"];
    suburl = [suburl stringByAppendingString:@"app000017"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kNewPhoneDynPwdDownloaderKey];
}
- (IBAction)commitButtonClicked:(id)sender
{
    [self.phoneTextField resignFirstResponder];
    [self.pwdTextField resignFirstResponder];
    NSString *validString = [self checkPasswordValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
    else
    {
        NSString *suburl = [NSString stringWithFormat:kNewPhoneCommitUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.accountId,phoneTextField.text,self.pwdTextField.text];
        suburl = [suburl stringByAppendingString:@"app000018"];
        NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kNewPhoneDownloaderKey];
        [[RYHUDManager sharedManager] startedNetWorkActivityWithText:@"修改手机号码..."];
    }
}

#pragma mark - Private methods

- (NSString *)checkPasswordValid
{
    //手机号长度11-11 手机号验证
    if(phoneTextField.text.length < 1)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"手机号"];
    else if(phoneTextField.text.length > 11)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"手机号"];
    else if(![NSString isMobileNumber:phoneTextField.text])
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000003E"],@"手机号"];

    else if(pwdTextField.text.length == 0)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"密码"];
    else if(pwdTextField.text.length > 6)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"密码"];
    else if(![pwdTextField.text isEqualToString:self.tempPwd])
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000004E"],@"密码",@"获取的密码"];
    else
        return nil;
}

- (void)enableSendButton
{
    self.sendButton.enabled = YES;
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(enableSendButton) object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle: @"新机号"];
    [self setLeftNaviItemWithTitle:@"返回" imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    CGSize scrollSize = self.myScrollView.contentSize;
    scrollSize.height = 270.f;
    self.myScrollView.contentSize = scrollSize;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.pwdTextField = nil;
        self.phoneTextField = nil;
        self.sendButton = nil;
        self.commitButton = nil;
        self.myScrollView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    self.pwdTextField = nil;
    self.phoneTextField = nil;
    self.sendButton = nil;
    self.commitButton = nil;
    self.myScrollView = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [tempPwd release];
    [sendButton release];
    [commitButton release];
    [pwdTextField release];
    [phoneTextField release];
    [myScrollView release];
    [super dealloc];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    if([downloader.purpose isEqualToString:kNewPhoneDynPwdDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            self.tempPwd = [dict objectForKey:@"verifycode"];
            self.sendButton.enabled = NO;
            [self performSelector:@selector(enableSendButton) withObject:nil afterDelay:30.f];
        }
        else
        {
            self.tempPwd = nil;
        }
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
    else if([downloader.purpose isEqualToString:kNewPhoneDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            [NYMemberCenterDataManager sharedManager].loginMember.phoneNum = self.phoneTextField.text;
            [[NSNotificationCenter defaultCenter] postNotificationName:kChangeNameSucceedNotification object:nil];
            //如果手机号修改成功，则回退到个人信息页
            NSArray *vcs = self.navigationController.viewControllers;
            [self.navigationController popToViewController:[vcs objectAtIndex:vcs.count-3] animated:YES];
        }
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if([downloader.purpose isEqualToString:kNewPhoneDynPwdDownloaderKey])
    {
        self.tempPwd = nil;
    }
    else if([downloader.purpose isEqualToString:kNewPhoneDownloaderKey])
    {
        
    }
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - notification methord

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect scrollFrame = self.myScrollView.frame;
    scrollFrame.size.height = self.view.frame.size.height - keyboardSize.height - 44;
    self.myScrollView.frame = scrollFrame;
}

- (void) keyboardWillHide:(NSNotification *)notification
{
    CGRect scrollFrame = self.myScrollView.frame;
    scrollFrame.size.height = self.view.frame.size.height - 44;
    self.myScrollView.frame = scrollFrame;
}

@end
